<template>
	<view class="contractManagement" :data-theme="theme">
		<view style="background-color: #fff;">
			<!-- <u-row customStyle="padding: 0px 30rpx;"> -->
			<view
				style="display: flex; flex-flow: row;justify-content: space-around; align-items: center; height: 40px;line-height: 40px;">
				<!-- 选择合同 -->
				<picker v-if="contractDateArray.length > 0" @change="contractDateChange" @cancel="contractDateCancel"
					@click="contractDateClick" :value="contractDateIndex" :range="contractDateArray" range-key="year"
					style="display: flex;">
					<view style="display: flex;flex-flow: row;">
						<view style="font-size: 14px;margin-right: 6rpx;">
							{{ contractDateArray[contractDateIndex].year }}
						</view>
						<u-icon :name="contractDateShow ? 'arrow-down-fill' : 'arrow-up-fill'" size="12"></u-icon>
					</view>
				</picker>

				<!-- 是否签署标签 -->
				<picker v-if="signArray.length > 0" @change="signChange" @cancel="signCancel" @click="signClick"
					:value="signIndex" :range="signArray" range-key="statusName" style="display: flex;">
					<view style="display: flex;flex-flow: row;">
						<view style="font-size: 14px;margin-right: 6rpx;">
							{{ signArray[signIndex].statusName}}({{signArray[signIndex].count}})
						</view>
						<u-icon :name="signShow ? 'arrow-down-fill' : 'arrow-up-fill'" size="12"></u-icon>
					</view>
				</picker>

			</view>
			<!-- </u-row> -->

		</view>
		<!-- 多选框未签署 -->
		<scroll-view scroll-y="true" class="content" v-if="notSign" @scrolltolower="handleScroll">
			<view class="check-all" v-if="(SigningInfo.length > 0)">
				<!-- <u-checkbox-group placement="row">
					<u-checkbox activeColor="red" shape="circle" :checked="isAllChecked" @change="onCheckAll"
						label="全选"></u-checkbox>
				</u-checkbox-group> -->
				<checkbox-group @change="onCheckAll">
					<label class="uni-list-cell uni-list-cell-pd" style="display: flex;line-height: 34rpx;">
						<view>
							<checkbox :checked="isAllChecked" />
						</view>
						<view>全选</view>
					</label>
				</checkbox-group>
				<view class="check-num">
					{{checked.length }}/{{SigningInfo.length}}
				</view>
			</view>

			<!-- <u-checkbox-group v-model="checked" placement="row">

				<view class="checke-list">
					<view class="checke-item" v-for="item in SigningInfo" :key="item.id">
						<view class="item-left">
							<u-checkbox activeColor="red" shape="circle" :checked="item.checked"
								:name="item.id"></u-checkbox>
							<view class="left-content">
								<view class="content-top">
									<view class="top-left">
									</view>
									<view class="top-right">
										{{ item.name }}
									</view>
								</view>
								<view class="content-bottom">
									有效期 {{ item.startTime ? item.startTime : ' '}} 至 {{ item.endTime ?  item.endTime : ' '}}
								</view>
							</view>
						</view>
						<view class="item-right" @click="checkClick(item.eurl,item)">
							查看
						</view>
					</view>
				</view>
			</u-checkbox-group> -->
			<checkbox-group @change="checkboxGroup" class="checke-list">
				<view class="uni-list-cell-pd checke-item" v-for="item in SigningInfo" :key="item.id">
					<view class="item-left">
						<view>
							<checkbox :value="item.id.toString()" :checked="item.checked" />
						</view>
						<view class="left-content">
							<view class="content-top">
								<view class="top-left">
								</view>
								<view class="top-right">
									{{ item.name }}
								</view>
							</view>
							<view class="content-bottom">
								有效期 {{ item.startTime ? item.startTime : ' '}} 至 {{ item.endTime ?  item.endTime : ' '}}
							</view>
						</view>
					</view>
					<view class="item-right" @click="checkClick(item.eurl,item)">
						查看
					</view>
				</view>
			</checkbox-group>
			<view>
				<u-empty v-if="!SigningInfo.length" style="padding-top: 50%;"
					icon="http://cdn.uviewui.com/uview/empty/data.png" text="当前没有合同需要您签署"> </u-empty>
				<uni-load-more v-else :status="moreStatus"> </uni-load-more>
			</view>
		</scroll-view>

		<!-- 已签署 -->
		<scroll-view scroll-y="true" class="content" v-if="finishSign" @scrolltolower="handleScroll">
			<view class="finish_sign" v-for="item in SigningInfo" :key="item.id">
				<view class="finish_sign_content">
					<view class="finish_sign_top">
						<view class="finish_sign_top_left">
							{{ item.name }}
						</view>
						<view class="finish_sign_top_right">
							<view class="top_rignt">{{signStatus[item.signingStatus]}}</view>
							<view style="color:black;" v-if="item.signingStatus == 31" @click="downloadClick(item)">下载
							</view>
						</view>
					</view>
					<view class="finish_sign_bottom">
						有效期 {{ item.startTime ? item.startTime : ' ' }} 至 {{item.endTime ? item.endTime : ' '}}
					</view>
				</view>

			</view>
			<view>
				<u-empty v-if="!SigningInfo.length" style="padding-top: 50%;"
					icon="http://cdn.uviewui.com/uview/empty/data.png" text="当前没有合同需要您签署"> </u-empty>
				<uni-load-more v-else :status="moreStatus"> </uni-load-more>
			</view>
		</scroll-view>
		<!-- 空数据展示 -->

		<!-- 底部批量签署 -->
		<view class="footer" v-if="notSign && (SigningInfo.length > 0)">
			<view class="alert" v-if="isAlert">
				签属合同请先勾选选框
			</view>
			<!-- <u-checkbox-group placement="row">
				<u-checkbox activeColor="red" shape="circle" :checked="required" @change="requiredChange"
					label="我已阅读完毕所有合同,同意批量签署" name="必选"></u-checkbox>
			</u-checkbox-group> -->
			<checkbox-group @change="requiredChange">
				<label class="uni-list-cell uni-list-cell-pd" style="display: flex;line-height: 34rpx;">
					<view>
						<checkbox :checked="required" />
					</view>
					<view>我已阅读完毕所有合同,同意批量签署</view>
				</label>
			</checkbox-group>
			<button class="bg_color footer-button" @click="go" shape="circle" style="padding: 20rpx;">批量签署</button>

		</view>

	</view>
</template>

<script>
	import {
		setThemeColor
	} from '../../utils/setTheme';
	import {
		getSigningInfoAPi,
		getSigningYearCountsAPi,
		getSigningStatusCountsAPi,
		getSignFlowUrlApi,
		updateSigningUrlApi
	} from "@/api/contract.js";
	let app = getApp();
	export default {
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,

				// 合同日期
				contractDateArray: [],
				// 合同日期
				contractDateIndex: 0, // 
				contractDateShow: true, //  合同箭头

				// 签署
				signArray: [],
				signIndex: 0, // 
				signShow: true, //  签署箭头
				// 签署状态
				signStatus: {
					31: '生效中',
					23: '已过期',
					33: '拒签',
					32: '签署失败'
				},
				//	全选
				isAllChecked: false,
				//	表单收集
				checked: [],
				required: false,
				isAlert: false, // 协议提示
				finishSign: false,
				notSign: true,
				params: {
					pages: 2,
					size: 20,
					status: '',
					year: '',
				},
				// 下拉数据加载状态
				moreStatus: 'more',
				// 获取信息列表
				SigningInfo: [],
				// 签署状态数量
				statusCount: '',
				// 获取签署数据参数
				signParams: {
					status: [20, 25],
					year: '',
				},
				// 获取正确e签宝链接
				eUrl: '',
				// 一个小时过期后的正确的下载链接
				downloadUrl: "",
				// 过期更新下载链接的params
				updateSigningUrlParams: {
					signFlowId: '',
				},
				// 过期更新下载链接的data
				updateSigningUrlData: []

			}
		},
		async onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			await this.getSigningYearCounts()
			await this.getSigningStatusCounts()
			this.params.year = this.contractDateArray[0].year
			this.params.status = this.signArray[0].status
			await this.getSigningInfo()
		},
		// 监听选中的数组
		watch: {
			checked(newVal, oldVal) {
				if (this.SigningInfo.length == this.checked.length) {
					this.isAllChecked = true
				} else {
					this.isAllChecked = false
				}
			},
		},
		methods: {
			// 下拉加载数据
			handleScroll() {
				if (this.moreStatus == 'more') {
					this.params.pages++
					this.getSigningInfo()
				}
			},
			// 下载链接过期后重新获取链接
			downloadClick(item) {
				this.updateSigningUrlParams.signFlowId = item.conFileList[0].signFlowId
				this.updateSigningUrlData.push(item.conFileList[0].id)
				// 获取当前日期与时间
				const today = new Date();
				const updateTime = new Date(item.conFileList[0].updateTime);
				// 计算更新时间与当前时间相差的秒数
				const timeDiffInSeconds = Math.floor((today - updateTime) / 1000);
				// 判断更新时间与当前时间相差是否至少一个小时（86400 秒）
				if (timeDiffInSeconds >= 60 * 60) {
					this.updateSigningUrlApi()
					location.href = this.downloadUrl
					console.log('更新时间距离今天至少相差一个小时');
				} else {
					location.href = item.conFileList[0].downloadUrl
					console.log('更新时间距禙今天不相差一个小时');
				}
			},
			// 查看
			async checkClick(url, item) {
				if (item.signingStatus == 20) {
					await this.getSignFlowUrl({
						signflowId: item.signingFlowId
					})
					location.href = this.eUrl
				} else {
					location.href = url
				}
			},
			// 必选事件
			requiredChange(val) {
				if (this.required === true) {
					this.required = false
					this.isAlert = true
				} else {
					this.required = true
					this.isAlert = false
				}
			},
			// 按钮事件
			go() {
				if (this.required === true) {
					// uni.navigateTo({
					// 	url: '/pages/invoice/invoiceRequestDetails/invoiceRequestDetails',
					// })
				} else {
					this.isAlert = true
				}

			},
			// 全选框
			onCheckAll(val) {
				let that = this;
				let isAllCheck = val.detail.value.length > 0;
				if (isAllCheck) {
					this.checked = []
					this.SigningInfo.forEach(item => {
						this.checked.push(item.id)
					})
					for (let item of this.SigningInfo) {
						item.checked = true;
					}

				} else {
					this.checked = []
					for (let item of this.SigningInfo) {
						item.checked = false;
					}
				}
			},
			checkboxGroup(checkboxValue) {
				let checkBoxValue = checkboxValue.detail.value.map((item) => JSON.parse(item))
				this.checked = checkBoxValue
			},

			// 下拉合同日期菜单
			async contractDateChange(e) {
				this.contractDateIndex = e.detail.value
				this.contractDateShow = true
				this.params.year = this.contractDateArray[this.contractDateIndex].year
				this.signParams.year = this.params.year
				await this.getSigningStatusCounts()
				await this.getSigningInfo(true)
			},
			// 合同日期取消事件
			contractDateCancel() {
				this.contractDateShow = true
			},
			// 合同日期点击事件
			contractDateClick() {
				this.contractDateShow = false
			},
			// 下拉签署状态菜单
			async signChange(e) {
				this.signIndex = e.detail.value
				this.signShow = true
				this.params.status = this.signArray[this.signIndex].status
				this.signParams.year = this.params.year
				if (this.signIndex == 0) {
					this.notSign = true
					this.finishSign = false
				} else {
					this.finishSign = true
					this.notSign = false
				}
				await this.getSigningInfo(true)
			},
			// 签署状态取消状态
			signCancel() {
				this.signShow = true
			},
			// 签署状态点击状态
			signClick() {
				this.signShow = false
			},

			// 获取合同日期的功能函数
			async getSigningYearCounts() {
				try {
					let result = await getSigningYearCountsAPi()
					if (result.code == 200) {
						this.contractDateArray = result.data
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e)
					this.$util.Tips({
						title: e
					})
				}
			},
			// 获取签署状态的功能函数
			async getSigningStatusCounts() {
				try {
					let result = await getSigningStatusCountsAPi(this.signParams)
					if (result.code == 200) {
						this.signArray = result.data
						this.params.status = this.signArray[0].status
						this.signIndex = 0
						this.notSign = true
						this.finishSign = false
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e)
					this.$util.Tips({
						title: e
					})
				}
			},
			// 合同列表的功能函数
			async getSigningInfo(status) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				if (status) {
					this.SigningInfo = []
					this.params.pages = 1
					this.params.size = 20
				}
				try {
					let result = await getSigningInfoAPi(this.params)
					if (result.code == 200) {
						let items = result.data.records
						if (items.length > 0) {
							if (result.data.pages == this.params.pages) {
								this.moreStatus = 'noMore'
							} else {
								this.moreStatus = 'more'
							}
							// 筛选所需要的合同数据
							let data = items.map(item => {
								let {
									contractName,
									...rest
								} = item
								return {
									name: contractName,
									...rest,
									disabled: false,
									checked: false,
								}
							})
							this.SigningInfo.push(...data)
						} else {
							this.moreStatus = 'noMore'
						}
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1500
						})
					}
					setTimeout(() => {
						uni.hideLoading()
					}, 300)
				} catch (e) {
					setTimeout(() => {
						uni.hideLoading()
					}, 300)
					//TODO handle the exception
					console.log(e)
					this.$util.Tips({
						title: e
					})
				}
			},
			// 获取正确的e签宝链接getSignFlowUrlApi
			async getSignFlowUrl(params) {
				try {
					let result = await getSignFlowUrlApi(params)
					if (result.code == 200) {
						this.eUrl = result.data
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					//TODO handle the exception
					console.log(e)
					this.$util.Tips({
						title: e
					})
				}
			},
			// 过期更新下载链接
			async updateSigningUrlApi() {
				try {
					let result = await updateSigningUrlApi(this.updateSigningUrlParams, this.updateSigningUrlData)
					if (result.code == 200) {
						this.downloadUrl = result.data.conFileList[0].downloadUrl
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 1500
						})
					}
				} catch (e) {
					//TODO handle the exception
					this.$util.Tips({
						title: e
					})
					console.log(e)
				}
			},
		},

	}
</script>

<style lang="scss" scoped>
	.bg_color {
		@include main_bg_color(theme);
		color: white;
	}

	page {
		display: flex;
		height: 100%;
		flex-direction: column;
		overflow: hidden;

		.contractManagement {
			display: flex;
			height: 100%;
			flex-direction: column;
			overflow: hidden;

			// 标签
			.footer {
				padding: 10px;

				.alert {
					color: red;
					margin-bottom: 10px;
				}

				.footer-button {
					margin-top: 10px;
				}

			}

			.sign_tags {
				display: flex;

				.sign_tag {
					margin-right: 20px;
					padding: 5px;
					line-height: 15px;
					border-radius: 5px;
				}

				// 选中的标签样式
				.bg_select {
					background-color: #eee;
					color: #fe5c2d;

				}
			}

			.finish_sign {
				background-color: white;
				// margin-top: 10px;
				padding: 10px;
				margin: 10px;
				border-radius: 5px;
			}

			.finish_sign_content {
				display: flex;
				flex-direction: column;
			}

			.finish_sign_top {
				display: flex;
				justify-content: space-between;
				margin-bottom: 10px;
				font-weight: bold;

				.finish_sign_top_right {
					color: #33a478;
					display: flex;

					.top_rignt {
						margin-right: 10px;
					}
				}
			}

			.finish_sign_bottom {
				opacity: .8;
			}
		}

		.content {
			margin-top: 10px;
			background-color: white;
			flex: 1;
			overflow: scroll;

			.check-all {
				margin-bottom: 20px;
				padding: 20px;
				padding-bottom: 0;
				display: flex;
				align-items: center;

				.check-num {
					margin-left: 5px;
				}

			}

			.checke-list {
				display: flex;
				flex-direction: column;
				width: 100%;

				.checke-item {
					display: flex;
					justify-content: space-between;
					align-items: center;

					border-top: 1px solid #eee;
					padding: 20px;

					.item-left {
						display: flex;

						.left-content {
							display: flex;
							flex-direction: column;
							margin-left: 5px;

							.content-top {
								display: flex;
								margin-bottom: 5px;

								.top-left {
									// background-color: red;
									// width: 15px;
									// height: 15px;
									// margin-right: 5px;
								}

							}

							.content-bottom {
								opacity: .6;
								margin-top: 5px;
							}
						}
					}

					.item-right {
						color: #5382cc;
						margin-right: 5px;
						flex-shrink: 0;
					}
				}
			}

		}
	}
</style>